const fs = require('fs-extra')
const path = require('path')
const webpack = require('webpack')
let getIPAdress = require('./build/get-ip-adress')
const CompileEventsPlugin = require('./build/compile-events-plugin')
const filterRemove = require('./build/filter-remove')
const webpackMsg = require('./build/msg-webpack')
let merge = require('webpack-merge')
const getWebpackConfig = require('./build/webpack.prod')
const argv = require('yargs').argv
const isAppMock = argv['app-mock']
const isAppTest = argv['app-test'] // 内网
process.env.APP_TEST = isAppTest
const isTest = argv['test'] === true // 有时候可能需要测试编译结果
const webpackConfig = getWebpackConfig(__dirname)

webpackConfig.plugins.unshift(
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify('production'),
      APP_TEST: JSON.stringify(isAppTest + '')
    }
  })
)

let prodConfig = {}

if (isAppMock) {
  webpackConfig.watch = true
  webpackConfig.devtool = 'source-map'
  webpackConfig.output.path = path.resolve(__dirname, './dist')
  webpackConfig.plugins.splice(3, 1)
  webpackConfig.entry.main.push('@/modules/ajax-mid/app.mock.js')

  // 开启即用服务器
  const server = require('http-server').createServer({
    root: webpackConfig.output.path
  })
  const portfinder = require('portfinder')
  portfinder.getPort((err, port) => {
    console.error(err)
    portfinder.basePort = 8080
    let host = getIPAdress()
    server.listen(port, host, function () {
      console.log(`http://${host}:${port}`)
    })
  })
} else if (isTest) {
  let outputPath = path.resolve(__dirname, './dist')
  prodConfig = {
    output: {
      path: outputPath
    },
    plugins: [
      new CompileEventsPlugin({
        compile () {
          filterRemove(outputPath, /.+/)
        },
        done () {
          filterRemove(outputPath, /\.(css)$/)
        }
      })
    ].concat(
      // 打包分析
      [(new (require('webpack-bundle-analyzer').BundleAnalyzerPlugin)())]
    )
  }
} else {
  // 打包输出路径设置：
  let outputPath = 'E:\\_work\\mobile_webview\\sdapp\\classevaluation\\src\\main\\assets'
  prodConfig = {
    output: {
      path: outputPath
    },
    plugins: [
      new CompileEventsPlugin({
        compile () {
          // filterRemove(outputPath, /js$/)
        },
        done () {
          filterRemove(outputPath, /(\.css|main\.js)$/)

          // 复制到 ios 输出目录
          fs.copySync(outputPath, './dist-ios', {
            filter: function (src, dest) {
              return /(assets|index\.html|main\.js|config.js)$/.test(src)
            }
          })
        }
      })
    ]
  }
}

// ios 路径处理。全部根路径
require('./build/ios-path-handle')(webpackConfig)

webpack(merge(webpackConfig, prodConfig), webpackMsg)
